<?php
namespace App\Models;

use App\Http\Requests\Request;

/**
 * 订单类
 */
class MOrder extends BaseModel
{
    public $table = "orders";

    public static $STATUS_PAY_OK = 1;   //已付款/待发货
    public static $STATUS_PAY_END = 2;  //已完结
    public static $STATUS_PAY_SEND = 3; //已发货

    /**
     * 关联用户 n:1
     */
    public function user()
    {
        return $this->hasOne(MUser::class, 'id', 'uid');
    }

    /**
     * 创建一个订单
     */
    public static function createOrder($user, $shoppingCar, $addr)
    {
        $order = new MOrder();
        $order->uid = $user->id;
        $order->no = onlyNo();
        $order->price = $shoppingCar->calc();

        $order->addr = $addr->city . "" . $addr->detail;
        $order->tel = $addr->name . " " . $addr->tel;

        $order->detail = $shoppingCar->detail();
        $order->time = time();
        $order->status = self::$STATUS_PAY_OK;
        return $order->save();
    }

    /**
     * 修改订单状态 发货
     */
    public function shipOrders($request)
    {
        $this->province = $request->province;
        $this->city = $request->city;
        $this->county = $request->county;
        $this->addr = $request->addr;
        $this->tel = $request->tel;
        $this->detail = $request->detail;
        $this->express_company_id = $request->express_company_id;
        $this->express_no = $request->express_no;
        $this->status = self::$STATUS_PAY_SEND;
        $this->send_time = time();
        return $this->save();
    }


    /**
     * 创建一个订单
     */
    public static function webCreateOrder($user, $product_ids,$product_nos, $request_money, $buy_nums, $detail)
    {
        $order = new MOrder();
        $order->uid = $user->id;
        $order->no = onlyNo();
//        $product = MProduct::find(intval($product_ids));
        $order->good_id = $product_ids;
        $order->good_no = $product_nos;
        $order->num = $buy_nums;
        $order->price = $request_money;

        $address = MAddress::where('uid', $user->id)->first();
        $order->province = $address->province;
        $order->city = $address->city;
        $order->county = $address->county;
        $order->addr = $address->addr;
        $order->tel = $address->tel;
        $order->detail = $detail;

        $order->create_time = time();
        $order->status = self::$STATUS_PAY_OK;
        return $order->save();
    }

    /**
     * 修改订单状态 完结
     */
    public function endOrders()
    {
        $this->status = 2;
        return $this->save();
    }
}